<form class="layui-form detail_form form-table-edit" action="" lay-filter="table_model_edit_form">
    <input type="hidden" name="table_id" value="#(detail.table_id)">

    #if(detail.table_id==null)
    <!-- 数据库表列表 -->
    <div class="layui-form-item">
        <div class="layui-inline" style="width: 50%">
            <label class="layui-form-label">数据库表</label>
            <div class="layui-input-inline" style="width: calc(100% - 120px);">
                <select id="db-table-select" name="db_table" lay-verify="" xm-select-search="" xm-select-radio=""
                        placeholder="选择参考数据库表" autocomplete="off" xm-select-height="38px" xm-select-skin="normal" xm-select="db-table-select" lay-filter="db-table-select">
                    <option value="">选择参考数据库表</option>
                </select>
            </div>
        </div>
        <div class="layui-inline">
            <div class="layui-input-inline" style="width: 100px;">
                <a class="layui-btn" lay-filter="btn-db-table-load">载入表配置</a>
            </div>
        </div>
    </div>
    #end
    <div class="layui-form-item">
        <label class="layui-form-label">表名</label>
        <div class="layui-input-block">
            <input type="text" name="table_key" value="#(detail.table_key)" lay-verify="required" placeholder="请输入表名" class="layui-input" autocomplete="off">
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label">显示名称</label>
        <div class="layui-input-block">
            <input type="text" name="table_name" value="#(detail.table_name)" lay-verify="required" placeholder="请输入显示名称" class="layui-input" autocomplete="off">
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label">模型包名</label>
        <div class="layui-input-block">
            <input type="text" name="model_package" value="#(detail.model_package)" lay-verify="required" placeholder="请输入模型包名" class="layui-input" autocomplete="off">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">字段列表</label>
        <div class="layui-input-block">
            <!-- 列表表格 -->
            <table id="field_config_table" lay-filter="field_config_table" style="width: 100%"></table>
            <!-- 显示名称 -->
            <script type="text/html" id="field_name_templet">
                <input type="hidden" name="field_id_{{d.field_id}}" value="{{d.field_id?d.field_id:''}}">
                <input type="hidden" name="field_order_{{d.field_id}}" value="{{d.field_order?d.field_order:''}}">
                <input type="text" name="field_name_{{d.field_id}}" value="{{d.field_name?d.field_name:''}}" required lay-verify="required" placeholder="显示标题" autocomplete="off" class="layui-input">
            </script>
            <!-- 字段名 -->
            <script type="text/html" id="field_key_templet">
                <input type="text" name="field_key_{{d.field_id}}" value="{{d.field_key?d.field_key:''}}" required lay-verify="required" placeholder="字段名称" autocomplete="off" class="layui-input">
            </script>
            <!-- 字段默认值 -->
            <script type="text/html" id="field_default_templet">
                <input type="text" name="field_default_{{d.field_id}}" value="{{d.field_default?d.field_default:''}}" required lay-verify="" placeholder="空值:NULL;空字符串:EMPTY_STRING" autocomplete="off" class="layui-input">
            </script>
            <!-- 字段类型 -->
            <script type="text/html" id="field_type_templet">
                <input type="text" name="field_type_{{d.field_id}}" value="{{d.field_type?d.field_type:''}}" required lay-verify="required" placeholder="字段类型" autocomplete="off" class="layui-input">
            </script>
            <!-- 字段长度 -->
            <script type="text/html" id="field_length_templet">
                <input type="number" name="field_length_{{d.field_id}}" value="{{d.field_length?d.field_length:''}}" placeholder="字段长度" autocomplete="off" class="layui-input">
            </script>
            <!-- 小数点 -->
            <script type="text/html" id="decimal_point_templet">
                <input type="number" name="decimal_point_{{d.field_id}}" value="{{d.decimal_point?d.decimal_point:''}}" title="" placeholder="小数点" autocomplete="off" class="layui-input">
            </script>
            <!-- 可空 -->
            <script type="text/html" id="is_nullable_templet">
                <input type="checkbox" name="is_nullable_{{d.field_id}}" {{d.is_nullable?'checked':''}} title="" lay-skin="primary">
            </script>
            <!-- 排序号 -->
            <script type="text/html" id="order_no_templet">
                <input type="number" name="order_no_{{d.field_id}}" value="{{d.order_no?d.order_no:'1'}}" title="" placeholder="排序号" autocomplete="off" class="layui-input">
            </script>
            <!-- 主键模板 -->
            <script type="text/html" id="is_primary_templet">
                <input type="checkbox" name="is_primary_{{d.field_id}}" {{d.is_primary?'checked':''}} title="" lay-skin="primary">
            </script>
            <!-- 每行操作按钮模板 -->
            <script type="text/html" id="field_config_templet">
                <input type="hidden" name="field_config_{{d.field_id}}" value='{{d.field_config?d.field_config:""}}'>
                <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="fieldConfig"><i class="layui-icon layui-icon-edit"></i>更多配置</a>
            </script>
            <!-- 每行操作按钮模板 -->
            <script type="text/html" id="field_row_toolbar">
                <a class="layui-btn layui-btn-xs" lay-event="add"><i class="layui-icon layui-icon-add-1"></i>添加</a>
                <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del"><i class="layui-icon layui-icon-delete"></i>删除</a>
            </script>
        </div>
    </div>
    <div class="detail_form_footer">
        <a class="layui-btn" lay-submit lay-filter="btn-table_model-submit">保存</a>
        <a class="layui-btn layui-btn-primary" lay-filter="btn-table_model-cancle">取消</a>
    </div>
</form>

<script>
    layui.use(['admin', 'form', 'laydate', 'formSelects'], function () {
        var $ = layui.$
            , admin = layui.admin
            , element = layui.element
            , layer = layui.layer
            , laydate = layui.laydate
            , table = layui.table
            , formSelects = layui.formSelects
            , form = layui.form;

        form.render(null, 'table_model_edit_form');


        //渲染创建时间日期时间选择器
        laydate.render({elem: '#create_datetime_type_datetime', type: 'datetime'});

        #if(detail.table_id == null)
        //渲染数据库表下拉选择器
        formSelects.data('db-table-select', 'server', {
            url: '/generator/table/dbTableList',
            keyName: 'TABLE_TITLE',
            keyVal: 'TABLE_NAME',
            searchName: 'table_title__op__like',
            showPage: true,
            size: 10,
        });
        formSelects.on('db-table-select', function (id, vals, val, isAdd, isDisabled) {
            if (isAdd) {
                let infos = val.name.split('(');
                let tableKey = infos.length > 0 ? infos[0] : '';
                let tableName = infos.length > 1 ? infos[1].replace(")", "") : "";
                form.val('table_model_edit_form', {
                    table_key: tableKey,
                    table_name: tableName ? tableName : tableKey,
                })
                loadTableFields(tableKey);
            }
        }, true);
        #end

        /* 自定义验证规则 */
        form.verify({
            title: function (value) {
                if (value.length < 5) {
                    return '标题至少得5个字符啊';
                }
            }
            , pass: [/(.+){6,12}$/, '密码必须6到12位']
            , content: function (value) {
                layedit.sync(editIndex);
            }
        });

        /* 监听提交 */
        form.on('submit(btn-table_model-submit)', function (data) {
            layer.msg('正在保存中，请稍候', {icon: 16});
            $.ajax({
                method: 'post',
                url: "/generator/table/save",
                data: data.field,
                dataType: 'json',
                success: function (rs) {
                    if (rs.success) {
                        layer.msg(rs.message || '保存成功', {icon: 6});
                        let config = #(detail.table_id == null ? '{page: {curr: 1}}' : '{}');
                        table.reload('table_model-table', config);
                        layer.closeAll('page'); //关闭所有页面层
                    } else {
                        layer.msg('保存失败,' + rs.message || '保存失败', {icon: 5});
                    }
                },
                error: function (a, b, c) {
                    layer.msg('请求异常，保存失败', {icon: 5});
                }
            });
            return false;
        });
        /* 监听取消 */
        $("[lay-filter=btn-table_model-cancle]").click(function () {
            layer.closeAll("page");
        });
        let tableCols = [[
            {field: 'is_primary', align: 'center', width: 80, title: '主键', event: 'is_primary', templet: "#is_primary_templet"},
            {field: 'field_key', align: 'center', title: '字段名', event: 'field_key', templet: "#field_key_templet"},
            {field: 'field_name', align: 'center', title: '显示名称', event: 'field_name', templet: "#field_name_templet"},
            {field: 'field_type', align: 'center', title: '字段类型', event: 'field_type', templet: "#field_type_templet"},
            {field: 'field_length', align: 'center', title: '字段长度', event: 'field_length', templet: "#field_length_templet"},
            {field: 'decimal_point', align: 'center', title: '小数点', event: 'decimal_point', templet: "#decimal_point_templet"},
            {field: 'is_nullable', align: 'center', width: 80, title: '可空', event: 'is_nullable', templet: "#is_nullable_templet"},
            {field: 'field_default', align: 'center', title: '默认值', event: 'field_default', templet: "#field_default_templet"},
            {field: 'order_no', align: 'center', width: 80, title: '排序号', event: 'order_no', templet: "#order_no_templet"},
            {title: 'field_config', align: 'center', width: 120, title: '扩展配置', fixed: 'right', templet: '#field_config_templet'},
            {title: '操作', fixed: 'right', width: 150, templet: '#field_row_toolbar'}
        ]]
        table.field_config_table_cols = tableCols;
        // 渲染表格数据
        table.render({
            id: 'field_config_table',
            elem: '#field_config_table',
            url: '/generator/field/list',
            where: {table_id: #(detail.table_id != null ? '"' + detail.table_id + '"' : '"_"')},
            loading: true,
            limit: 999,
            page: false, //开启分页
            cols: tableCols,
            parseData: function (res) { //res 即为原始返回的数据
                let data;
                if (res.success) {
                    data = res.data;
                }
                if (!data || data.length <= 0) {
                    data = [{field_id: '-1', field_order: 1, field_key: 'id', field_name: '主键', field_type: 'int', field_default: 'NULL'}]
                }
                res.data = data;
                return res;
            },
            done: function () {
            }
        });

        // 监听表格行事件
        table.on("tool(field_config_table)", eventListener);

        // 事件监听
        function eventListener(obj) {
            let event = obj.event;
            let data = obj.data;
            let tableData = table.cache.field_config_table;
            switch (event) {
                case 'add':
                    renderFieldConfigTable(addTableData(tableData, data));
                    break;
                case 'del':
                    renderFieldConfigTable(removeTableData(tableData, data));
                    break;
                case 'fieldConfig':
                    let postData = getFieldModel(data);
                    layui.$.post('/generator/table/fieldConfigPage', postData,
                        function (str) {
                            layer.open({
                                type: 1,
                                title: data.field_name + ' - 字段扩展配置',
                                maxmin: true,
                                area: ['600px', '500px'],
                                content: str,
                            })
                        });
                    break;
            }
        }

        function getFieldModel(rowData) {
            let formVals = form.val('table_model_edit_form');
            let fieldId = rowData.field_id
            rowData.field_key = formVals['field_key_' + fieldId];
            rowData.field_name = formVals['field_name_' + fieldId];
            rowData.field_type = formVals['field_type_' + fieldId];
            rowData.field_length = formVals['field_length_' + fieldId];
            rowData.decimal_point = formVals['decimal_point_' + fieldId];
            rowData.order_no = formVals['order_no_' + fieldId];
            rowData.is_primary = formVals['is_primary_' + fieldId] == 'on';
            rowData.is_nullable = formVals['is_nullable_' + fieldId] == 'on';
            rowData.field_default = formVals['field_default_' + fieldId];
            return rowData;
        }

        if (!table.fun) {
            table.fun = {field_config_table: {}};
        }
        table.fun.field_config_table.getFieldModel = getFieldModel;

        // 添加表格数据
        function addTableData(tableData, preData) {
            let newTableData = [];
            let isAdd = false;
            for (let i = 0; i < tableData.length; i++) {
                let fieldModel = getFieldModel(tableData[i]);
                newTableData.push(fieldModel);
                if (preData != null) {
                    if (preData.field_id == fieldModel.field_id) {
                        newTableData.push({field_id: '-', field_default: 'NULL'})
                        isAdd = true;
                    }
                }
            }
            if (!isAdd) {
                newTableData.push({field_id: '-', field_default: 'NULL'})
            }
            newTableData.forEach(function (item, idx) {
                if (item.field_id.indexOf && item.field_id.indexOf("-") == 0) {
                    item.field_id = "-" + (idx + 1)
                }
            })
            return newTableData;
        }

        // 删除表格数据
        function removeTableData(tableData, data) {
            let newTableData = [];
            for (let i = 0; i < tableData.length; i++) {
                if (data != null) {
                    if (data.field_id == tableData[i].field_id) {
                        continue;
                    }
                }
                newTableData.push(tableData[i]);
            }
            newTableData.forEach(function (item, idx) {
                if (item.field_id.indexOf && item.field_id.indexOf("-") == 0) {
                    item.field_id = "-" + (idx + 1)
                }
            })
            return newTableData;
        }

        function renderFieldConfigTable(data) {
            if (!data || data.length <= 0) {
                data = [{field_id: '-1', field_order: 1, field_key: 'id', field_name: '主键', field_type: 'int', field_default: 'NULL'}]
            }
            // 重新设置排序号
            data.forEach((item, idx) => item.field_order = idx + 1);
            table.render({
                id: "field_config_table",
                elem: '#field_config_table',
                data: data,
                cols: tableCols,
                limit: 999,
            })
        }

        /* 监听载入表配置 */
        let loadTableFields = function (tableKey) {
            let dbTable = tableKey;
            if (!dbTable) {
                dbTable = form.val('table_model_edit_form').db_table;
            }
            if (!dbTable) {
                layer.msg('没有选择要载入的数据表！', {icon: 5});
                return;
            }
            $.ajax({
                method: 'post',
                url: "/generator/table/dbFieldList",
                data: {"table_key": dbTable},
                dataType: 'json',
                success: function (rs) {
                    if (rs.success) {
                        form.val('table_model_edit_form', {})
                        renderFieldConfigTable(convertDbFieldList(rs.data));
                    } else {
                        layer.msg('载入数据表信息失败,' + rs.message || '载入数据表信息失败', {icon: 5});
                    }
                },
                error: function (a, b, c) {
                    layer.msg('请求异常，载入数据表信息失败', {icon: 5});
                }
            });
            return false;
        };

        /**
         * 转换db字段列表为表格数据data
         * @param dbList
         */
        function convertDbFieldList(dbList) {
            let data = [];
            dbList.forEach(function (item, idx) {
                let columnTypes = item.COLUMN_TYPE.split("(");
                let fieldType = columnTypes.length > 0 ? columnTypes[0] : '';
                let fieldLength = columnTypes.length > 1 ? columnTypes[1].replace(")", "") : '';
                let decimalPoint = '';
                if (fieldLength.indexOf(".") >= 0) {
                    let strings = fieldLength.split('.');
                    fieldLength = strings[0];
                    decimalPoint = strings[1];
                }
                let isAutoIncrease = item.EXTRA == 'auto_increment';
                let fieldConfig = {}
                if (isAutoIncrease) {
                    fieldConfig.isAutoIncrease = isAutoIncrease;
                }
                data.push({
                    field_id: '-' + (idx + 1),
                    field_key: item.COLUMN_NAME,
                    field_name: item.COLUMN_COMMENT ? item.COLUMN_COMMENT : item.COLUMN_NAME,
                    field_type: fieldType,
                    field_length: fieldLength,
                    decimal_point: decimalPoint,
                    order_no: idx+1,
                    is_nullable: item.IS_NULLABLE == 'YES',
                    is_primary: item.COLUMN_KEY == 'PRI',
                    field_order: idx,
                    field_config: JSON.stringify(fieldConfig),
                    field_default: item.COLUMN_DEFAULT == ''?'EMPTY_STRING':(item.COLUMN_DEFAULT==null||item.COLUMN_DEFAULT==undefined)?'NULL':item.COLUMN_DEFAULT,
                    _source: item,
                });
            })
            return data;
        }

        $('[lay-filter=btn-db-table-load]').click(function () {
            loadTableFields();
        });

    });
</script>